angular.module('reportDetailModule', []).factory('reportDetailService', function() {
    return {
        Illustrate: function(basicObj, xData, yData, documentID, bool3D, toolTips) {
            //Title  -- Must
            var title = {
                text: basicObj.title
            };
            //sub Title -- optional
            var subtitle = {
                text: basicObj.subtitle
            };
            //X轴 -- Must
            var xAxis = {
                categories: xData,
                // tickInterval: 3,
                labels: {
                    // x: 15
                    style: { "color": "#fff", "font-size": "10px", "font-family": "微软雅黑", "font-weight": "normal" }
                }
            };
            //Y轴 -- Must
            /**
             * text: yAxis_text -- 图Y轴最左侧，代表纵轴的具体含义
             */
            var yAxis = {
                title: {
                    text: basicObj.yAxis_text,
                    style: { "color": "#fff", "font-size": "13px", "font-family": "微软雅黑", "font-weight": "normal" }
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            };
            //simple config when Mousr Hover to Show tips
            var tooltip = {
                shared: true,
                useHTML: true,
                style: {
                    color: 'orange',
                    fontSize: '11px',
                    fontWeight: 'normal',
                    fontFamily: 'Courir new'
                }
            };
            //charts legend
            var legend = {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                itemStyle: {
                    'fontSize': '10px',
                    'font-family': 'Microsoft YaHei'
                },
                borderWidth: 0
            };
            //Chart Global Config
            /**
             * type -- Charts Type: line/column/pie ...
             * name -- 数据点名称(鼠标悬停时显示的Y轴含义)
             */
            var series = [{
                type: basicObj.series_type,
                name: basicObj.series_name,
                data: yData,
                color: basicObj.color,
                colorByPoint: true, //使用系统随机配色, 否则使用上一个选项color值作为图颜色
                lineWidth: 0.5,
                dataLabels: {
                    enabled: true, //允许显示 数据标签
                    //format: '{x} \t {y} mm',
                    style: {
                        fontSize: '15px'
                            //fontFamily: ''
                            //color: 'green'
                    }
                    // formatter: function() {
                    //     return this.x + "\t" + this.y + " mm";
                    // }

                }
            }];
            //Config For 3D Charts
            var chart = {
                //type: basicObj.series_type,
                margin: 75,
                options3d: {
                    enabled: bool3D,
                    alpha: 15,
                    beta: 23,
                    viewdistance: 25,
                    depth: 65
                }
            };

            var json = {};
            json.title = title;
            json.subtitle = subtitle;
            json.xAxis = xAxis;
            json.yAxis = yAxis;
            json.tooltip = tooltip;
            json.legend = legend;
            json.series = series;
            json.chart = chart;
            $(documentID).highcharts(json);
        },
        IllustratePie: function(jsonData, Title, documentID, listType) {
            var listData = '';
            if (listType !== "") {
                listData = this._getListsData(jsonData, listType);
            } else {
                listData = this.getListData(jsonData);
            }

            var arrayData = this._formatPieData(listData);
            this._createPie(Title, documentID, arrayData);
        },
        _IllustratePie: function(jsonData, Title, documentID, listType) {
            //For story_AccidentOnlineCount
            var listData = this._getAccidentListsData(jsonData, listType);
            var arrayData = this._formatPieData(listData);
            this._createPie(Title, documentID, arrayData);
        },
        createTable: function(captionTitle, tHead_arr, jsonData, sourceType) {
            var listData = '';
            if (sourceType === "") {
                listData = this.getListData(jsonData); //listData[0]-> title， listData[1]-> value
            } else if (sourceType == "businessDirectionList" || sourceType == "ProblemTypeList") {
                listData = this._getAccidentListsData(jsonData, sourceType);
            }

            //Todo
            //caption
            var caption = '<table class="table table-bordered table-hover "><caption class="text-muted h4">' + captionTitle + '</caption>';
            //thead
            var tableHead = '<thead><tr><th>' + tHead_arr[0] + '</th><th>' + tHead_arr[1] + '</th></tr></thead><tbody>';
            //tbody
            var tableBody = '';
            for (var i = 0; i < listData[0].length; i++) {
                tableBody += '<tr><td>' + listData[0][i] + '</td><td>' + listData[1][i] + '</td></tr>';
            }

            return caption + tableHead + tableBody + '</tbody></table>';

        },
        _createRiskDetailListTable: function(captionTitle, tHeadArr, jsonData) {
            var dataList = this._getRiskDetailListData(jsonData);
            if (dataList.length > 0) {
                //表头上的Table标题
                var caption = '<table class="table table-bordered table-hover " style="table-layout:fixed"><caption class="text-muted h4">' + captionTitle + '</caption>';
                var tempHead = '';
                for (var i in tHeadArr) {
                    tempHead += '<th>' + tHeadArr[i] + '</th>';
                }
                var tableHead = '<thead><tr>' + tempHead + '</tr></thead><tbody>'; //完成head拼接
                //tbody

                var tableBody = '';
                for (var j in dataList) {
                    tableBody += '<tr>' + '<td>' + dataList[j].createTime + '</td>' + '<td>' + dataList[j].businessDirection + '</td>' + '<td>' + dataList[j].story + '</td>' + '<td>' + dataList[j].riskDetail + '</td>' + '<td>' + dataList[j].solution + '</td>' + '</tr>';
                }

                return caption + tableHead + tableBody + '</tbody></table>';
            } else {
                return "";
            }
        },

        _createAccidentOnlineDetailTable: function(captionTitle, tHeadArr, jsonData) {

            var dataList = this._getAccidentOnlineDetailListData(jsonData);
            //console.log("accidentList:");
            if (dataList.length !== 0) {
                //表头上的Table标题
                var caption = '<table class="table table-bordered table-hover "><caption class="text-muted h4">' + captionTitle + '</caption>';
                var tempHead = '';
                for (var i in tHeadArr) {
                    tempHead += '<th>' + tHeadArr[i] + '</th>';
                }
                var tableHead = '<thead><tr>' + tempHead + '</tr></thead><tbody>'; //完成head拼接
                //tbody


                var tableBody = '';
                for (var j in dataList) {
                    var URL;
                    if (dataList[j].url === undefined || dataList[j].url == "") {
                        URL = "http://client-qatools.jdb-dev.com/JDBToolsPlatform/404.html";
                    } else {
                        URL = dataList[j].url;
                    }
                    tableBody += '<tr>' + '<td><a href="' + URL + '" target="_blank">' + dataList[j].number + '</a></td>' + '<td>' + dataList[j].accidentTheme + '</td>' + '<td>' + dataList[j].priority + '</td>' + '<td>' + dataList[j].createTime + '</td>' + '<td>' + dataList[j].businessDirection + '</td>' + '<td>' + dataList[j].problemCause + '</td>' + '</tr>';
                }

                return caption + tableHead + tableBody + '</tbody></table>';
            } else {
                return "";
            }

        },
        _createPie: function(Title, documentID, arrayData) {
            var chart = {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            };
            var title = Title;

            var tooltip = {
                shared: true,
                useHTML: true,
                style: {
                    color: 'orange',
                    fontSize: '8px',
                    fontWeight: 'normal',
                    fontFamily: 'Microsoft YaHei'
                },
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            };
            var plotOptions = {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        useHTML: true,
                        maxStaggerLines: 1,
                        //format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
                            fontFamily: 'Microsoft YaHei',
                            fontSize: '8px'
                        },
                        formatter: function() {
                            var text;
                            if (this.point.name.length > 3) {
                                text = '<a title="' + this.point.name + '">' + this.point.name.substring(0, 2) + '</a>';
                            } else {
                                text = this.point.name;
                            }
                            return text + ": " + this.percentage.toFixed(2) + "%";
                        }

                    },
                    showInLegend: true //图例
                }
            };
            var legend = {
                //图例位置
                layout: 'vertical', //显示形式，支持水平horizontal和垂直vertical
                align: 'right', //对其方式，默认为center
                verticalAlign: 'top',
                borderWidth: 0,
                itemStyle: {
                    'fontSize': '10px',
                    'font-family': 'Microsoft YaHei'
                },
                useHTML: true,
                labelFormatter: function() {
                    var legendMsg;
                    legendMsg = '<a title="' + this.name + '">';
                    if (this.name.length > 5) {
                        legendMsg += (this.name).substring(0, 3);
                        legendMsg += '...';
                        legendMsg += (this.name).substring(this.name.length - 2, this.name.length);
                    } else {
                        legendMsg += this.name;
                    }
                    legendMsg += '</a>';
                    return legendMsg;
                }
            };
            var series = [{
                type: 'pie',
                name: '百分比: ',
                data: arrayData
            }];
            var credits = {
                enabled: false
            };

            var json = {};
            json.chart = chart;
            json.title = title;
            json.tooltip = tooltip;
            json.series = series;
            json.plotOptions = plotOptions;
            json.legend = legend;
            json.credits = credits;
            $(documentID).highcharts(json);
        },
        getListData: function(dataList) {
            var xData = [];
            var yData = [];
            for (var i = 0; i < dataList.list.length; i++) {
                xData.push(dataList.list[i].title);
                yData.push(parseFloat(dataList.list[i].count));
            }
            return Array(xData, yData);
        },
        _getListsData: function(datas, type) {
            var xData = [];
            var yData = [];
            var List = '';
            if (type == "client") {
                List = datas.clientList;
            } else {
                List = datas.serverList;
            }
            for (var i = 0; i < List.length; i++) {
                xData.push(List[i].title);
                yData.push(parseFloat(List[i].count));
            }
            return Array(xData, yData);
        },
        _getAccidentListsData: function(jsonData, type) {
            //For story_AccidentOnlineCount
            var xData = [];
            var yData = [];
            var List = '';
            if (type == "businessDirectionList") {
                List = jsonData.businessDirectionList;
            } else {
                List = jsonData.ProblemTypeList;
            }
            for (var i = 0; i < List.length; i++) {
                xData.push(List[i].title);
                yData.push(parseFloat(List[i].count));
            }
            return Array(xData, yData);
        },
        _getRiskDetailListData: function(json) {
            //风险明细列表
            return json.RiskDetailList;
        },
        _getAccidentOnlineDetailListData: function(json) {
            //线上事故列表
            return json.AccidentOnlineDetailList;
        },
        _formatPieData: function(arrayData) {
            var xAxisData = arrayData[0],
                yAxisData = arrayData[1];
            var pieArrayData = [];
            for (var i in xAxisData) {
                pieArrayData.push([xAxisData[i], yAxisData[i]]);
            }
            return pieArrayData;
        },
        createColumnCharts: function(Title, documentID, jsonData, seriesName) {
            var AxisData = this.getListData(jsonData);
            var basicObj = {};
            basicObj.title = Title;
            basicObj.subtitle = "";
            basicObj.yAxis_text = "";
            basicObj.tooltip = "";
            basicObj.series_type = "column";
            basicObj.series_name = seriesName;
            basicObj.color = "#bed742";

            this.Illustrate(basicObj, AxisData[0], AxisData[1], documentID, false, "");
        },
        _createColumnCharts: function(Title, documentID, jsonData, seriesName, listType) {
            //for process_BugTypeCount
            var AxisData = this._getListsData(jsonData, listType);
            var basicObj = {};
            basicObj.title = Title;
            basicObj.subtitle = "";
            basicObj.yAxis_text = "";
            basicObj.tooltip = "";
            basicObj.series_type = "column";
            basicObj.series_name = seriesName;
            basicObj.color = "#bed742";

            this.Illustrate(basicObj, AxisData[0], AxisData[1], documentID, false, "");
        },
        processRiskCountCharts: function(jsonData, id) {
            //1.3 研发过程中风险统计
            AxisData = this.getListData(jsonData);
            var basicObj = {};
            basicObj.title = "风险来源统计";
            basicObj.subtitle = "";
            basicObj.yAxis_text = "";
            basicObj.tooltip = "";
            basicObj.series_type = "column";
            basicObj.series_name = "风险数";
            basicObj.color = "#bed742";

            this.Illustrate(basicObj, AxisData[0], AxisData[1], id, false, "");
        },
        hideElements: function(elementArr) {
            //隐藏报告富文本区域(ng-bind-html的div元素)
            for (var i in elementArr) {
                var className = "div[ng-bind-html='" + elementArr[i] + "']";
                document.querySelector(className).style.visibility = "hidden";
            }
        },
        checkDataFormat: function(dataString) {
            //校验日期格式是否为: YYYY-mm-dd
            var r = dataString.match(/^(\d{4})-(\d{2})-(\d{2})$/i);
            if (!r) {
                return false; //不符合
            } else {
                return true; //符合
            }
        },
        sortBy: function(filed, rev, primer) {
            //针对数字、int float 排序、a/b/c...
            //filed json array ,false升序， TRUE- 将序, primer parseInt/parseFloat...
            rev = (rev) ? -1 : 1;
            return function(a, b) {
                a = a[filed];
                b = b[filed];
                if (typeof(primer) != 'undefined') {
                    a = primer(a);
                    b = primer(b);
                }
                if (a < b) { return rev * -1; }
                if (a > b) { return rev * 1; }
                return 1;
            };
        },
        sortJSON: function(jsonArr, orderBy, key) {
            if (orderBy == "asc") {
                //正序，升序
                return jsonArr.sort(sortBy(key, false, parseInt));
            } else if (orderBy == "desc") {
                //倒序
                return jsonArr.sort(sortBy(key, true, parseInt));
            } else {
                console.log("传入的orderBy不正确!");
                return;
            }

        }
    };
});